package com.uyayo.oms.notepad.controller;

import com.uyayo.framework.common.annotation.MethodName;
import com.uyayo.framework.common.exception.ParentNotFoundException;
import com.uyayo.framework.message.enums.ResultMsgEnum;
import com.uyayo.framework.message.model.Result;
import com.uyayo.oms.notepad.vo.FavoriteCategoryVO;
import com.uyayo.oms.system.biz.ParamBiz;
import com.uyayo.notepad.entity.FavoriteCategory;
import com.uyayo.notepad.model.FavoriteCategoryCondition;
import com.uyayo.notepad.service.FavoriteCategoryService;
import com.uyayo.system.authority.entity.SysUser;
import com.uyayo.ucenter.entity.Member;
import com.uyayo.ucenter.service.MemberService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.dozer.DozerBeanMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Objects;


/**
 * 
 * Title: FavoriteCategoryController
 * Description:资源的Controller
 *
 * @author 乐乐科技.胡逢君
 * @date 2017-4-13下午4:03:35
 * @version 1.0
 */
@Controller
@RequestMapping("/notepad/favorite/category")
public class FavoriteCategoryController {

	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	private final FavoriteCategoryService favoriteCategoryService;

	private final ParamBiz paramBiz;

	private  final  MessageSource messageSource;

	private final DozerBeanMapper dozerBeanMapper;

	private final MemberService memberService;

	@Autowired
	public FavoriteCategoryController(FavoriteCategoryService favoriteCategoryService, ParamBiz paramBiz, MessageSource messageSource, DozerBeanMapper dozerBeanMapper, MemberService memberService) {
		this.favoriteCategoryService = favoriteCategoryService;
		this.paramBiz = paramBiz;
		this.messageSource = messageSource;
		this.dozerBeanMapper = dozerBeanMapper;
		this.memberService = memberService;
	}

	/**
	 * 获得资源treeGrid
	 */
	@ResponseBody
	@RequestMapping("tree")
	@MethodName(value="记事管理->记事本分类管理->查询",type=2)
	public List<FavoriteCategory> tree(FavoriteCategoryCondition favoriteCategoryCondition) {

		if(!Objects.isNull(favoriteCategoryCondition.getUsername())){
			Member member = memberService.getMemberByUsername(favoriteCategoryCondition.getUsername());
			if(member!=null){
				favoriteCategoryCondition.setMemberId(member.getId());
			}
		}
		return favoriteCategoryService.selectFavoriteCategory(favoriteCategoryCondition);
	}

	/**
	 * 获得资源treeGrid
	 */
	@ResponseBody
	@RequestMapping("treeGrid")
	@MethodName(value="记事管理->记事本分类管理->查询",type=2)
	public List<FavoriteCategory> treeGrid(FavoriteCategoryCondition favoriteCategoryCondition) {

		if(!Objects.isNull(favoriteCategoryCondition.getUsername())){
			Member member = memberService.getMemberByUsername(favoriteCategoryCondition.getUsername());
			if(member!=null){
				favoriteCategoryCondition.setMemberId(member.getId());
			}
		}
		if(Objects.isNull(favoriteCategoryCondition.getParentId())){
			favoriteCategoryCondition.setParentId(0L);
		}
        return favoriteCategoryService.selectFavoriteCategory(favoriteCategoryCondition);
	}


	/**
	 * 列表首页
	 */
	@RequestMapping("index")
	@MethodName(value="记事管理->记事本分类管理")
	public ModelAndView index(ModelAndView modelAndView,String parentId,String username) {
		modelAndView.addObject("parentId",parentId);
		modelAndView.addObject("username",username);
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"notepad/favorite/category/index");
		return modelAndView;
	}


	/**
	 * 查看资源信息
	 */
	@RequestMapping("view")
	public ModelAndView view(ModelAndView modelAndView,Long id) {
		FavoriteCategory favoriteCategory  = favoriteCategoryService.selectByKey(id);
		Member member = memberService.getMemberById(favoriteCategory.getMemberId());
		FavoriteCategoryVO favoriteCategoryVO = dozerBeanMapper.map(favoriteCategory,FavoriteCategoryVO.class);
		favoriteCategoryVO.setUsername(member.getUsername());
		modelAndView.addObject("favoriteCategory",favoriteCategoryVO);
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"notepad/favorite/category/view");
		return modelAndView;
	}

	/**
	 * 添加资源信息
	 */
	@RequestMapping(value = "add", method = RequestMethod.GET)
	public ModelAndView add(ModelAndView modelAndView) {
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"notepad/favorite/category/add");
		return modelAndView;
	}
	
	/**
	 * 保存
	 */
	@ResponseBody
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@MethodName(value="记事管理->记事本分类管理->添加",type=2)
	public Result add(@Validated FavoriteCategoryVO favoriteCategoryVO , Errors errors, HttpServletRequest request) {
		try {
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
			}
			Subject subject = SecurityUtils.getSubject();
			SysUser sysUser = (SysUser) subject.getPrincipal();
			Member member = memberService.getMemberByUsername(favoriteCategoryVO.getUsername());
			if(member==null){
				String message = messageSource.getMessage(ResultMsgEnum.USER_NOT_EXIST.getKey(),new Object[]{}, request.getLocale());
				logger.warn(message);
				return Result.error(ResultMsgEnum.USER_NOT_EXIST.code(),message);
			}
			FavoriteCategory favoriteCategory = dozerBeanMapper.map(favoriteCategoryVO,FavoriteCategory.class);
			favoriteCategory.setMemberId(member.getId());
			favoriteCategory.setHasChildren(false);
			favoriteCategory.setCreateBy(sysUser.getLoginname());
			favoriteCategory.setCreateTime(new Date());
			favoriteCategoryService.saveFavoriteCategory(favoriteCategory);
		} catch (ParentNotFoundException e){
			String message = messageSource.getMessage(ResultMsgEnum.PARENT_NOT_FOUND.getKey(),new Object[]{}, request.getLocale());
			logger.warn(message,e.getMessage());
			return Result.error(ResultMsgEnum.PARENT_NOT_FOUND.code(),message);
        }catch(Exception e) {
			String message = messageSource.getMessage(ResultMsgEnum.INTERNAL_SERVER_ERROR.getKey(),new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.error(ResultMsgEnum.INTERNAL_SERVER_ERROR.code(),message);
        }
		String message = messageSource.getMessage(ResultMsgEnum.SAVE_SUCCESS.getKey(),new Object[]{}, request.getLocale());
		return Result.success(ResultMsgEnum.SAVE_SUCCESS.code(),message);
	}

	@ResponseBody
	@RequestMapping(value = "update", method = RequestMethod.GET)
	public ModelAndView update(ModelAndView modelAndView,Long id) {
		FavoriteCategory favoriteCategory = favoriteCategoryService.selectByKey(id);
		Member member = memberService.getMemberById(favoriteCategory.getMemberId());
		FavoriteCategoryVO favoriteCategoryVO = dozerBeanMapper.map(favoriteCategory,FavoriteCategoryVO.class);
		favoriteCategoryVO.setUsername(member.getUsername());
		modelAndView.addObject("favoriteCategory",favoriteCategoryVO);
		modelAndView.setViewName(paramBiz.getManagerTemplatesPrefix()+"notepad/favorite/category/update");
		return modelAndView;
	}

	/**
	 * 更新
	 */
	@ResponseBody
	@RequestMapping(value = "update", method = RequestMethod.POST)
	@MethodName(value="记事管理->记事本分类管理->修改资源",type=2)
	public Result update(@Validated FavoriteCategoryVO favoriteCategoryVO , Errors errors, HttpServletRequest request) {
		try {
			if (errors.hasErrors()) {
				return Result.errorAndMsg(errors.getFieldError().getDefaultMessage());
			}
			if (StringUtils.isEmpty(favoriteCategoryVO.getId())) {
                String message = messageSource.getMessage(ResultMsgEnum.PARAMETER_ERROR.getKey(),new Object[]{}, request.getLocale());
                logger.warn(message);
				return Result.error(ResultMsgEnum.PARAMETER_ERROR.code(),message);
            }

			if (favoriteCategoryVO.getParentId() != null && Objects.equals(favoriteCategoryVO.getId(), favoriteCategoryVO.getParentId())) {
				String message = messageSource.getMessage(ResultMsgEnum.PARENT_SELF_ERROR.getKey(),new Object[]{}, request.getLocale());
				logger.warn(message);
				return Result.error(ResultMsgEnum.PARENT_SELF_ERROR.code(),message);
			}

			Subject subject = SecurityUtils.getSubject();
			SysUser sysUser = (SysUser) subject.getPrincipal();
			Member member = memberService.getMemberByUsername(favoriteCategoryVO.getUsername());
			if(member==null){
				String message = messageSource.getMessage(ResultMsgEnum.USER_NOT_EXIST.getKey(),new Object[]{}, request.getLocale());
				logger.warn(message);
				return Result.error(ResultMsgEnum.USER_NOT_EXIST.code(),message);
			}
			FavoriteCategory favoriteCategory = dozerBeanMapper.map(favoriteCategoryVO,FavoriteCategory.class);
			favoriteCategory.setMemberId(member.getId());
			favoriteCategory.setUpdateBy(sysUser.getLoginname());
			favoriteCategory.setUpdateTime(new Date());
			int updateCount = favoriteCategoryService.updateFavoriteCategory(favoriteCategory);
			if(updateCount<=0){
				String message = messageSource.getMessage(ResultMsgEnum.SAVE_FAIL.getKey(),new Object[]{}, request.getLocale());
                logger.warn(message);
				return Result.error(ResultMsgEnum.SAVE_FAIL.code(),message);
			}
			String message = messageSource.getMessage(ResultMsgEnum.SAVE_SUCCESS.getKey(),new Object[]{}, request.getLocale());
			return Result.success(ResultMsgEnum.SAVE_SUCCESS.code(),message);
		} catch (ParentNotFoundException e){
            String message = messageSource.getMessage(ResultMsgEnum.PARENT_NOT_FOUND.getKey(),new Object[]{}, request.getLocale());
            logger.warn(message,e.getMessage());
			return Result.error(ResultMsgEnum.PARENT_NOT_FOUND.code(),message);
		} catch(Exception e) {
			String message = messageSource.getMessage(ResultMsgEnum.INTERNAL_SERVER_ERROR.getKey(),new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.error(ResultMsgEnum.INTERNAL_SERVER_ERROR.code(),message);
		}
	}

    /**
     *删除
     * @param id 资源id
     * @param request HttpServletRequest
     * @return Result
     */
	@ResponseBody
	@RequestMapping(value="delete",method = RequestMethod.DELETE)
	@MethodName(value="记事管理->记事本分类管理->删除资源",type=2)
	public Result deleteFavoriteCategory(Long id, HttpServletRequest request){

        try {
            if (StringUtils.isEmpty(id)) {
				String message = messageSource.getMessage(ResultMsgEnum.PARAMETER_ERROR.getKey(),new Object[]{}, request.getLocale());
				logger.error(message);
				return Result.error(ResultMsgEnum.PARAMETER_ERROR.code(),message);
            }
            int deleteCount = favoriteCategoryService.deleteFavoriteCategory(id);
            if(deleteCount<=0){
				String message = messageSource.getMessage(ResultMsgEnum.DELETE_FAIL.getKey(),new Object[]{}, request.getLocale());
				logger.error(message);
				return Result.error(ResultMsgEnum.DELETE_FAIL.code(),message);
            }
        } catch(Exception e) {
			String message = messageSource.getMessage(ResultMsgEnum.INTERNAL_SERVER_ERROR.getKey(),new Object[]{}, request.getLocale());
			logger.error(message,e);
			return Result.error(ResultMsgEnum.INTERNAL_SERVER_ERROR.code(),message);
        }
		String message = messageSource.getMessage(ResultMsgEnum.DELETE_SUCCESS.getKey(),new Object[]{}, request.getLocale());
		return Result.success(ResultMsgEnum.DELETE_SUCCESS.code(),message);
	}
}
